//
//  XinAddCoffeeVC.swift
//  XinGuoSearch
//
//  Created by 李东 on 2024/4/9.
//

import UIKit
import SnapKit

class XinAddCoffeeVC: XinBaseVC {
    
    lazy var scrollView = UIScrollView()
    lazy var line = UIView()
    lazy var topLabel = UILabel()
    lazy var topImgView = UIImageView(image: UIImage(named: "img_coffee"))
    lazy var bgView = UIImageView(image: UIImage(named: "img_coffee_bg"))
    lazy var contentView = UIView()
    lazy var dateLabel = UILabel()
    lazy var cancelBtn = UIButton(type: .custom)
    lazy var confirmBtn = UIButton(type: .custom)
    var alertView: UIView!
    
    var coffeeTF: UITextField!
    var typeTF: UITextField!
    var mgTF: UITextField!
    var timeTF: UITextField!
    
    var model = XinCoffeeModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = .init(hex: 0xACC1FE)
        hideNavgaitionBar()
        initUI()
        showPopBtn = true
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        contentView.snp.updateConstraints { make in
            make.bottom.equalTo(-(CGFloat.screenHeight-contentView.maxY))
        }
    }
    
    lazy var df: DateFormatter = {
        let temo = DateFormatter()
        temo.dateFormat = "yyyy-MM-dd"
        return temo
    }()
    
    lazy var df1: DateFormatter = {
        let temo = DateFormatter()
        temo.dateFormat = "yyyy-MM-ddHH:mm"
        return temo
    }()
    
    func initUI() {
        view.insetsLayoutMarginsFromSafeArea = false
        scrollView.contentInsetAdjustmentBehavior = .never
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        line.backgroundColor = .clear
        scrollView.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(1)
            make.width.equalTo(view)
        }
        
        topLabel.textColor = .black
        topLabel.font = UIFont.Medium(ofSize: 18)
        topLabel.text = "添加今日咖啡记录"
        scrollView.addSubview(topLabel)
        topLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(CGFloat.navHeight + 40)
        }
        
        bgView.contentMode = .scaleToFill
        scrollView.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(topLabel.snp.bottom).offset(20)
        }
        
        scrollView.addSubview(topImgView)
        topImgView.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.centerY.equalTo(bgView.snp.top)
            make.width.equalTo(73)
            make.height.equalTo(111)
        }
        
        contentView.backgroundColor = .white
        contentView.layer.cornerRadius = 4
        contentView.layer.masksToBounds = true
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(topImgView.snp.bottom).offset(15)
            make.bottom.equalToSuperview()
        }
        
        dateLabel.textColor = .init(hex: 0x5456FF)
        dateLabel.font = UIFont.Medium(ofSize: 18)
        dateLabel.text = df.string(from: Date())
        contentView.addSubview(dateLabel)
        dateLabel.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(20)
            make.height.equalTo(26)
        }
        
        let itemView1 = createItemView(title: "咖 啡", isTime: false)
        contentView.addSubview(itemView1)
        itemView1.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.top.equalTo(dateLabel.snp.bottom).offset(20)
            make.height.equalTo(48)
        }
        
        let itemView2 = createItemView(title: "杯 型", isTime: false)
        contentView.addSubview(itemView2)
        itemView2.snp.makeConstraints { make in
            make.left.right.height.equalTo(itemView1)
            make.top.equalTo(itemView1.snp.bottom).offset(12)
        }
    
        let itemView3 = createItemView(title: "咖啡因", isTime: false)
        contentView.addSubview(itemView3)
        itemView3.snp.makeConstraints { make in
            make.left.right.height.equalTo(itemView1)
            make.top.equalTo(itemView2.snp.bottom).offset(12)
        }
        
        let itemView4 = createItemView(title: "时 间", isTime: true)
        itemView4.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(seletTimeHandle)))
        contentView.addSubview(itemView4)
        itemView4.snp.makeConstraints { make in
            make.left.right.height.equalTo(itemView1)
            make.top.equalTo(itemView3.snp.bottom).offset(12)
        }
        
        cancelBtn.backgroundColor = .init(hex: 0xE7E7E7)
        cancelBtn.titleLabel?.font = UIFont.Medium(ofSize: 16)
        cancelBtn.setTitleColor(.black, for: .normal)
        cancelBtn.layer.cornerRadius = 27.5
        cancelBtn.layer.masksToBounds = true
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.addTarget(self, action: #selector(cancelHandle), for: .touchUpInside)
        contentView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(itemView4.snp.bottom).offset(20)
            make.height.equalTo(55)
            make.right.equalTo(contentView.snp.centerX).offset(-10)
        }
        
        confirmBtn.backgroundColor = .init(hex: 0xFFB000)
        confirmBtn.titleLabel?.font = UIFont.Medium(ofSize: 16)
        confirmBtn.setTitleColor(.black, for: .normal)
        confirmBtn.layer.cornerRadius = 27.5
        confirmBtn.layer.masksToBounds = true
        confirmBtn.setTitle("确定", for: .normal)
        confirmBtn.addTarget(self, action: #selector(okHandle), for: .touchUpInside)
        contentView.addSubview(confirmBtn)
        confirmBtn.snp.makeConstraints { make in
            make.right.equalTo(-15)
            make.top.equalTo(itemView4.snp.bottom).offset(20)
            make.height.equalTo(55)
            make.bottom.equalToSuperview().offset(-30)
            make.left.equalTo(contentView.snp.centerX).offset(10)
        }
        
    }
    
    @objc func seletTimeHandle() {
        view.endEditing(true)
        let vc = XinTimePickerVC()
        vc.selectCallBack = {[weak self] time in
            guard let self = self else { return  }
            self.model.time = time
            self.timeTF.text = time
        }
        vc.modalPresentationStyle = .overFullScreen
        present(vc, animated: true)
    }
    
    @objc func cancelHandle() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc func okHandle() {
        if coffeeTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入咖啡名称")
            return
        }
        if typeTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入咖啡杯型")
            return
        }
        if mgTF.text?.isEmpty ?? true {
            showHUDTextOnly("请输入咖啡因数量")
            return
        }
        if timeTF.text?.isEmpty ?? true {
            showHUDTextOnly("请选择时间")
            return
        }
        model.ymd = dateLabel.text!
        model.coffee = coffeeTF.text!
        model.time = timeTF.text!
        model.count = 1
        model.mg = Int(mgTF.text!) ?? 0
        let ts = df1.date(from: model.ymd + model.time)?.timeIntervalSince1970
        model.ts = Int(ts ?? 0)
        
        var mg = model.mg
        XinDataHelper.shared.getLocalList().forEach { mm in
            if mm.ymd == model.ymd {
                mg += mm.mg
            }
        }
        if mg > 300 {
            showWarnAlert()
        }else{
            saveHandle()
        }
 
    }
    
    func saveHandle()  {
        XinDataHelper.shared.addData(model: model)
        showHUDTextOnly("保存成功") {[weak self] in
            guard let self = self else {
                return
            }
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func createItemView(title: String, isTime: Bool) -> UIView {
        let tempView = UIView()
        tempView.backgroundColor = .init(hex: 0xF8F8F8)
        tempView.layer.cornerRadius = 4
        tempView.layer.masksToBounds = true
        tempView.isUserInteractionEnabled = true
        
        let leftLabel = UILabel()
        leftLabel.textColor = .black
        leftLabel.text = title
        leftLabel.font = UIFont.Medium(ofSize: 16)
        tempView.addSubview(leftLabel)
        leftLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(12)
            make.width.equalTo(65)
        }
        
        let line = UIView()
        line.backgroundColor = .init(hex: 0x979797)
        tempView.addSubview(line)
        line.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.width.equalTo(0.5)
            make.height.equalTo(30)
            make.left.equalTo(leftLabel.snp.right)
        }
        let tf = UITextField()
        tf.font = UIFont.Medium(ofSize: 16)
        tf.textColor = .black
        tf.placeholder = isTime ? "请选择" : "请输入"
        tempView.addSubview(tf)

        if title == "咖 啡" {
            coffeeTF = tf
            tf.snp.makeConstraints { make in
                make.left.equalTo(line.snp.right).offset(20)
                make.top.bottom.equalToSuperview()
                make.right.equalTo(-20)
            }
        }else if title == "杯 型" {
            typeTF = tf
            tf.snp.makeConstraints { make in
                make.left.equalTo(line.snp.right).offset(20)
                make.top.bottom.equalToSuperview()
                make.right.equalTo(-20)
            }
        }else if title == "咖啡因" {
            mgTF = tf
            mgTF.keyboardType = .numberPad
            tf.snp.makeConstraints { make in
                make.left.equalTo(line.snp.right).offset(20)
                make.top.bottom.equalToSuperview()
                make.right.equalTo(-40)
            }
            let mgLabel = UILabel()
            mgLabel.textColor = .black.withAlphaComponent(0.23)
            mgLabel.font = UIFont.Medium(ofSize: 16)
            mgLabel.text = "mg"
            mgLabel.textAlignment = .center
            tempView.addSubview(mgLabel)
            mgLabel.snp.makeConstraints { make in
                make.top.bottom.right.equalToSuperview()
                make.width.equalTo(40)
            }
        }else {
            timeTF = tf
            timeTF.isEnabled = false
            tf.snp.makeConstraints { make in
                make.left.equalTo(line.snp.right).offset(20)
                make.top.bottom.equalToSuperview()
                make.right.equalTo(-40)
            }
            let arrowImgView = UIImageView(image: UIImage(named: "icon_arrow_right_black"))
            arrowImgView.contentMode = .center
            tempView.addSubview(arrowImgView)
            arrowImgView.snp.makeConstraints { make in
                make.right.top.bottom.equalToSuperview()
                make.width.equalTo(40)
            }
        }
        return tempView
    }

    
    func showWarnAlert()  {
        alertView = UIView(frame: UIScreen.main.bounds)
        alertView.backgroundColor = .black.withAlphaComponent(0.5)
        view.addSubview(alertView)
        let tempView = UIView()
        tempView.backgroundColor = .white
        tempView.layer.cornerRadius = 15
        tempView.layer.masksToBounds = true
        alertView.addSubview(tempView)
        tempView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(304)
//            make.height.equalTo(180)
        }
        
        let label = UILabel()
        label.font = UIFont.Medium(ofSize: 18)
        label.textColor = .black
        label.text = "您今日咖啡因摄入量已超标\n试试其他饮品吧"
        label.textAlignment = .center
        label.numberOfLines = 0
        tempView.addSubview(label)
        label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(25)
        }
        
        let contineBtn = UIButton(type: .custom)
        contineBtn.backgroundColor = .init(hex: 0xFFB000)
        contineBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        contineBtn.setTitleColor(UIColor.black, for: .normal)
        contineBtn.layer.cornerRadius = 25
        contineBtn.layer.masksToBounds = true
        contineBtn.setTitle("添加", for: .normal)
        contineBtn.addTarget(self, action: #selector(continueHandle), for: .touchUpInside)
        tempView.addSubview(contineBtn)
        contineBtn.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(tempView.snp.centerX).offset(-8)
            make.height.equalTo(50)
            make.bottom.equalTo(-20)
            make.top.equalTo(label.snp.bottom).offset(25)
        }
        
        let cancelBtn = UIButton(type: .custom)
        cancelBtn.backgroundColor = .init(hex: 0xE7E7E7)
        cancelBtn.layer.cornerRadius = 25
        cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        cancelBtn.setTitleColor(UIColor.black, for: .normal)
        cancelBtn.layer.masksToBounds = true
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.addTarget(self, action: #selector(hideAlert), for: .touchUpInside)
        tempView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.right.equalTo(-15)
            make.left.equalTo(tempView.snp.centerX).offset(8)
            make.height.equalTo(50)
            make.centerY.equalTo(contineBtn)
        }
    }
    
    
    @objc func continueHandle() {
        hideAlert()
        saveHandle()
    }
    
    @objc func hideAlert() {
        alertView.removeFromSuperview()
        alertView = nil
    }


}
